import { CommonModal } from "@/pages/OrderModule/common/components/CommonModal";
import { Form, Radio, Space, Checkbox, Input, Button } from "antd";
import OrderAreaRadioGroup from "../../components/OrderAreaRadioGroup1";
import OrderNumberCount from "../../components/OrderNumberCount";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { useState, useRef, useEffect, useMemo } from "react";
import CommonLoading from "@/components/CommonLoading";
import { TagOutlined } from "@ant-design/icons";
import SetTag from "@/components/SelectTag/SetTag";
import { filter, isEmpty } from "lodash";
import styles from "./index.module.less";
import { queryTagList, updateLabelOP } from "../../../../services";
import Iconfont from "@/components/IconFont";
import { labelTypeMap, labelColorMap } from "@/utils/config";

const CheckboxGroup = Checkbox.Group;

//title
const RenderTitle = props => {
	return (
		<div className={styles.titleWrap}>
			<div className={styles.titleLeft}></div>
			<div className={styles.titleContent}>{props.title}</div>
		</div>
	);
};


/** 设置订单标签 */
function SetOrderLabelModal(props) {
	const { searchForm, orderList, selectKeys, recordData, handleCancel, isBatch, handleOk } = props;
	const [showNumber, setShowNumber] = useState({});
	//选择标签
	const [selectTag, setSelectTag] = useState([]);
	//标签列表
	const [tagList, setTagList] = useState([]);
	//搜索框内容
	const [inputVal, setInputVal] = useState();
	const [tagVisible, setTagVisible] = useState(false);
	const [loading, setLoading] = useState(false);

	const filterIds = useRef(undefined);

	//真正用于渲染的标签列表
	const realData = useMemo(() => {
		if (inputVal) {
			return filter(tagList, val => {
				if (labelColorMap[val.name]) {
					return labelColorMap[val.name].includes(inputVal);
				} else {
					return val.name.includes(inputVal);
				}
			});
		}
		return tagList;
	}, [inputVal, tagList]);

	const [form] = Form.useForm();

	// useEffect(() => {
	// 	if (!isEmpty(recordData)) {
	// 		const arr = recordData.labelList.map(item => item.labelId);
	// 		setSelectTag(arr);
	// 	}
	// }, [recordData]);

	useEffect(() => {
		getTagList();
	}, []);

	//获取标签列表
	const getTagList = async () => {
		setLoading(true);
		const { success, data } = await queryTagList();
		setLoading(false);
		if (success) {
			setTagList(data);
		}
	};

	//修改标签
	const updateLabel = async val => {
		let params = { ids: isBatch ? filterIds.current || selectKeys : [recordData.id], labelIds: selectTag, type: val.type };
		setLoading(true);
		const { success, data } = await updateLabelOP(params);
		setLoading(false);
		if (success) {
			if (isBatch) {
				if (filterIds.current.length) {
					handleOk(1, filterIds.current);
				} else {
					handleOk(2);
				}
			} else {
				handleOk(recordData.id);
			}
		}
	};

	//点击确定
	const onOk = () => {
		if (loading) {
			return false;
		}
		form
			.validateFields()
			.then(val => {
				updateLabel(val);
			})
			.catch(err => {});
	};

	//标签组
	const renderTag = () => {
		const [indeterminate, setIndeterminate] = useState(true);
		const [checkAll, setCheckAll] = useState(false);
		//单选变更
		const onChange = list => {
			setSelectTag(list);
			setIndeterminate(!!list.length && list.length < realData.length);
			setCheckAll(list.length === realData.length);
		};

		//全选事件
		const onCheckAllChange = e => {
			setSelectTag(e.target.checked ? realData.map(v => v.id) : []);
			setIndeterminate(false);
			setCheckAll(e.target.checked);
		};
		return (
			<div style={{ marginTop: "24px" }}>
				<Input
					style={{ marginBottom: "16px" }}
					value={inputVal}
					onChange={e => setInputVal(e.target.value)}
					placeholder="请输入标签内容"
				/>
				<div className={styles.checkAll}>
					<RenderTitle title="选择标签" />
					<Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
						全选
					</Checkbox>
				</div>
				<CheckboxGroup className={styles.checkWrap} value={selectTag} onChange={onChange}>
					{realData.map(v => {
						return (
							<Checkbox className={styles.checkBox} value={v.id} key={v.id}>
								{labelTypeMap[v.name] ? (
									<div className={styles.iconBox}>
										<span style={{ fontSize: 14 }}>{labelColorMap[v.name]}</span>
										<Iconfont type={labelTypeMap[v.name]} />
									</div>
								) : (
									<span>{v.name}</span>
								)}
							</Checkbox>
						);
					})}
				</CheckboxGroup>
			</div>
		);
	};

	const orderAreaRadioProps = {
		searchForm,
		selectKeys,
		orderList,
		states: [10, 30],
		title: "（所有订单状态都支持）",
		updateShowNumer(obj, ids) {
			filterIds.current = ids;
			setShowNumber(obj);
		}
	};

	//维护自定义标签弹框
	const SetTagProps = {
		handleCancel() {
			setTagVisible(false);
			getTagList();
		}
	};

	return (
		<CommonModal
			title={{ title: "设置订单标签" }}
			open={true}
			width="840px"
			onOk={onOk}
			onCancel={handleCancel}
			footer={
				<div className={styles.footer}>
					<div className={styles.operaWrap} onClick={() => setTagVisible(true)}>
						<TagOutlined className={styles.operaIcon} />
						维护自定义标签
					</div>
					<div>
						<Button onClick={handleCancel}>取消</Button>
						<Button onClick={onOk} type="primary">
							确定
						</Button>
					</div>
				</div>
			}
		>
			<Form
				initialValues={{
					type: "1"
				}}
				form={form}
			>
				{isBatch && (
					<>
						<OrderAreaRadioGroup {...orderAreaRadioProps} />
						<OrderNumberCount
							data={[
								{ label: "待审核", value: showNumber[10], type: "warning" },
								{ label: "异常", value: showNumber[30], type: "error" }
							]}
						/>
					</>
				)}
				<SubTitle symbol as="s2" title="*标签修改方式" wrapStyle={{ margin: "16px 0" }} />
				<Form.Item name="type" rules={[{ required: true, message: `请选择标签修改方式` }]}>
					<Radio.Group>
						<Space direction="vertical">
							<Radio value="1">添加以下标签到订单（重复添加的标签不会重复显示）</Radio>
							<Radio value="2">从订单移除以下标签</Radio>
						</Space>
					</Radio.Group>
				</Form.Item>
			</Form>
			<div>{renderTag()}</div>
			{tagVisible && <SetTag {...SetTagProps} />}
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default SetOrderLabelModal;
